<?php

/**
 * user actions.
 *
 * @package    jiazhang
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions
{

       //我关注的人
   public function executeAttention_me(sfWebRequest $request){
       $action_user_id = (int)$request->getParameter('person_id',0);
       
       $user_ids = Doctrine::getTable('UserAttention')->createQuery()->where('attention_user_id = ?',$action_user_id)->execute();
       $user = array();
       $users = array();
       $i=0;
       foreach($user_ids as $user){
           if($user->getActionUser() == null) continue;
           $users[$i]['id'] = $user->getActionUser()->getId();
           $users[$i]['name'] = $user->getActionUser()->getNickname();
           $users[$i]['icon'] = $user->getActionUser()->getCover();
           $idea_num = Doctrine::getTable('Skill')->createQuery()->where('user_id = ?',$user->getActionUser()->getId())->count();
           $users[$i]['ideaNum'] = $idea_num;
           $patriarchNum = Doctrine::getTable('PatriarchArticle')->createQuery()->where('user_id = ?',$user->getActionUser()->getId())->count();
           $users[$i]['patriarchNum'] = $patriarchNum;
           $fansNum = Doctrine::getTable('UserAttention')->createQuery()->where('attention_user_id = ?',$user->getActionUser()->getId())->count();
           $users[$i]['fansNum'] = $fansNum;
           $i++;
       }
       
        return $this->renderText(json_encode($users));
   } 
    
    //我关注的人
   public function executeMy_attention(sfWebRequest $request){
       $action_user_id = (int)$request->getParameter('person_id',0);
       
       $user_ids = Doctrine::getTable('UserAttention')->createQuery()->where('action_user_id = ?',$action_user_id)->execute();
       $users = array();
       
       $i=0;
       foreach($user_ids as $user){
           if($user->getAttentionUser() == null)               continue;
           $users[$i]['id'] = $user->getAttentionUser()->getId();
           $users[$i]['name'] = $user->getAttentionUser()->getNickname();
           $users[$i]['icon'] = $user->getAttentionUser()->getCover();
           $idea_num = Doctrine::getTable('Skill')->createQuery()->where('user_id = ?',$user->getAttentionUser()->getId())->count();
           $users[$i]['ideaNum'] = $idea_num;
           $patriarchNum = Doctrine::getTable('PatriarchArticle')->createQuery()->where('user_id = ?',$user->getAttentionUser()->getId())->count();
           $users[$i]['patriarchNum'] = $patriarchNum;
           $fansNum = Doctrine::getTable('UserAttention')->createQuery()->where('attention_user_id = ?',$user->getAttentionUser()->getId())->count();
           $users[$i]['fansNum'] = $fansNum;
           $i++;
       }
        return $this->renderText(json_encode($users));
   } 
    
    
   public function executeAttention(sfWebRequest $request){
       
       $msg = array('error'=>0,'msg'=>'');
       if($request->isMethod('POST')){
           
            $action_user_id = (int)$request->getParameter('m_person_id',0);
            $attention_user_id = (int)$request->getParameter('person_id',0);
            
            $has_user = Doctrine::getTable('UserAttention')
                    ->createQuery()
                    ->where('action_user_id = ?',$action_user_id)
                    ->andWhere('attention_user_id = ?',$attention_user_id)
                    ->execute();
            
            if(count($has_user) > 0){
                
                $has_user->delete();
                $msg['error'] = 0;
                $msg['msg'] = '您已经取消关注了！';
                return $this->renderText(json_encode($msg));
                
            }else{
                
                $attention = new UserAttention();
                $attention->setActionUserId($action_user_id)->setAttentionUserId($attention_user_id)->save();
                $msg['error'] = 0;
                $msg['msg'] = '您已经关注成功了！';
                return $this->renderText(json_encode($msg));
            }
            
       }
       
       return $this->renderText(json_encode($msg));
   }
    
    
   //根据用户ID获取用户数据
  public function executeGet_userinfo(sfWebRequest $request){
     $user_id = (int)$request->getParameter('person_id',0);
     //当前用户id
     $action_user_id = (int)$request->getParameter('m_person_id',0);
     
     $user = Doctrine::getTable('User')->findOneById($user_id);
     $msg = array('error'=>'','msg'=>'');
     
        if(!$user){
            $msg['error'] = 1;
            $msg['msg'] = '用户不存在，请联系管理员';
            return $this->renderText(json_encode($msg));
        }
        
        $has_user = $user;
        $msg = array('error'=>0,'msg'=>'数据获取成功');
              
      $is_attention = Doctrine::getTable('UserAttention')->createQuery()->where('action_user_id = ?',$action_user_id)->andWhere('attention_user_id = ?',$user_id)->count();   
      $skill_num = Doctrine::getTable('Skill')->createQuery()->where('user_id = ?',$user_id)->andWhere('status <> 3')->count();
      $attention_num = Doctrine::getTable('UserAttention')->createQuery()->where('action_user_id = ?',$user_id)->count();
      $concerned_num = Doctrine::getTable('UserAttention')->createQuery()->where('attention_user_id = ?',$user_id)->count();
      $patriarch_num = Doctrine::getTable('PatriarchArticle')->createQuery()->where('user_id = ?',$user_id)->andWhere('display = 1')->count();
      
      $msg['person'] = array(
              'id'=>$has_user->getId(),
              'phone'=>$has_user->getPhone(),
              'name'=>$has_user->getNickname(),
              'icon'=>$has_user->getCover(),
              'area'=>$has_user->getProvince().'-'.$has_user->getCity(),
              'familyRole'=>User::$roles[$has_user->getRole()],
              'reg_time'=>$has_user->getCreatedAt(),
              'page_cover'=>$has_user->getPageCover(),
              'skill_num'=>$skill_num,
              'province'=>$has_user->getProvince(),
              'city'=>$has_user->getCity(),
            'attention_num'=>$attention_num,
            'concerned_num'=>$concerned_num,
            'patriarch_num'=>$patriarch_num,
            'isAttention'=>$is_attention
          );

      
      $msg['person']['children'] = array();
      $childs = $has_user->getChilds();

      if(count($childs) > 0){
          $i = 0;
          foreach($childs as $child){
              $msg['person']['children'][$i]['id'] = $child->getId();
              $msg['person']['children'][$i]['name'] = $child->getName();
              $msg['person']['children'][$i]['age'] = $child->getChildOld();
              $msg['person']['children'][$i]['sex'] = $child->getSexToString();
              $msg['person']['children'][$i]['year'] = $child->getYear();
              $msg['person']['children'][$i]['month'] = $child->getMonth();
              $i++;
          }
      }
      
      return $this->renderText(json_encode($msg));
  }  
    
  public function executeEdit_password(sfWebRequest $request){
      sfConfig::set('sf_web_debug',false);
      $msg = array('error'=>'','msg'=>'');
      
      if($request->isMethod('POST')){
            $phone = $request->getParameter('phone',0);
            $phone_code = (int)$request->getParameter('phone_code',0);
            $password = $request->getParameter('password',0);
            
            if(strlen($phone) != 11){
                $msg['error'] = 1;
                $msg['msg'] = '手机号码格式错误！请重新填写';
//                return $this->renderText(json_encode($msg));
           }else{
               $user = Doctrine::getTable('User')->findOneByPhone($phone);
               
               if(!$user){
                    $msg['error'] = 1;
                    $msg['msg'] = '用户不存在！请重新填写';
                    return $this->renderText(json_encode($msg));
               }
               
               $has_phone_code = Doctrine::getTable('SmsMessage')->createQuery()->where('phone = ?',$phone)->andWhere('code = ?',$phone_code)->andWhere('is_use = 0')->execute();
               
               if(count($has_phone_code) == 1){
                   $sms = $has_phone_code->getFirst();
                   $sms->setIsUse(1)->save();
                   Doctrine::getTable('SmsMessage')->createQuery()->where('phone = ?',$phone)->andWhere('is_use = 0')->delete()->execute();
                   $user->setPassword($password)->save();
                    $msg['error'] = 0;
                    $msg['msg'] = '密码修改成功！';
               }else{
                    $msg['error'] = 1;
                    $msg['msg'] = '验证码错误！请重新填写';
               }
           }
      }
      
      return $this->renderText(json_encode($msg));
  }  
  
  public function executeComplete_info(sfWebRequest $request){
      sfConfig::set('sf_web_debug',false);
      if($request->isMethod('POST')){
          $id = (int)$request->getParameter('id',0);
          $user = Doctrine::getTable('User')->findOneById($id);
          $msg = array('error'=>'','msg'=>'');
          
          if(!$user){
              $msg['error'] = 1;
              $msg['msg'] = '用户不存在，请联系管理员';
              return $this->renderText(json_encode($msg));
          }
          
          $cover = trim($request->getParameter('picture',''));
          $nickname = trim($request->getParameter('name',''));
          $province = trim($request->getParameter('province',''));
          $city = trim($request->getParameter('city',''));
          $childrens = json_decode(trim($request->getParameter('children','')));
          $children_num = (int)$request->getParameter('children_num',0);
          $role = $request->getParameter('familyRole',1);
          $page_cover = $request->getParameter('page_cover','');
          
          if(strpos($cover,'!usercover') === FALSE){
              $user->setCover($cover);
          }
          
          $user->setNickname($nickname)->setRole($role)->setProvince($province)->setCity($city)->setPageCover($page_cover)->save();
          Doctrine::getTable('UserChild')->createQuery()->where('user_id = ?',$id)->delete()->execute();
          
          if($children_num > 0 && !is_null($childrens)){
            foreach($childrens as $children){
                if(is_object($children) && $children instanceof stdClass){
                  $user_children = new UserChild();
                  $user_children->setUserId($user->getId())->setName($children->name)->setYear($children->year)->setMonth($children->month)->setSex($children->sex)->save();
                }
            }
          }
          
          $msg['error'] = 0;
          $msg['msg'] = '数据保存成功！';
          return $this->renderText(json_encode($msg));
      }
  }
    
    
  public function executeLogin(sfWebRequest $request){
      sfConfig::set('sf_web_debug',false);
      if($request->isMethod('POST')){
          $phone = floatval($request->getParameter('phone',0));
          $password = trim($request->getParameter('password',0));
          $msg = array('error'=>0,'msg'=>'');
          
          if(strlen($phone) != 11){
              $msg = array('error'=>1,'msg'=>'手机号码格式错误，请检查！');
              return $this->renderText(json_encode($msg));
          }elseif(strlen($password) < 32){
              $msg = array('error'=>1,'msg'=>'密码错误，请检查！');
              return $this->renderText(json_encode($msg));
          }else{
             $has_user = Doctrine::getTable('User')->findOneByPhone($phone);
              
              if($has_user){
                  
                  if($has_user->getStatus() == 0){
                      $msg = array('error'=>1,'msg'=>'用户被禁用，请联系管理员！');
                      return $this->renderText(json_encode($msg));
                  }
                  
                  $user_password = $has_user->getPassword();
                  
                  if($password == $user_password){
                      $msg = array('error'=>0,'msg'=>'成功登入！');
                      $msg['person'] = array(
                              'id'=>$has_user->getId(),
                              'phoneNum'=>$has_user->getPhone(),
                              'name'=>$has_user->getNickname(),
                              'icon'=>$has_user->getCover(),
                              'area'=>$has_user->getProvince().'-'.$has_user->getCity(),
                              'familyRole'=>User::$roles[$has_user->getRole()],
                              'reg_time'=>$has_user->getCreatedAt(),
                              'page_cover'=>$has_user->getPageCover()
                          );
                      $msg['person']['children'] = array();
                      $childs = $has_user->getChilds();
                      
                      if(count($childs) > 0){
                          $i = 0;
                          foreach($childs as $child){
                              $msg['person']['children'][$i]['id'] = $child->getId();
                              $msg['person']['children'][$i]['name'] = $child->getName();
                              $msg['person']['children'][$i]['age'] = $child->getChildOld();
                              $msg['person']['children'][$i]['sex'] = $child->getSexToString();
                              $msg['person']['children'][$i]['year'] = $child->getYear();
                              $msg['person']['children'][$i]['month'] = $child->getMonth();
                              $i++;
                          }
                      }
                      
                      return $this->renderText(json_encode($msg));
                  }else{
                      $msg = array('error'=>1,'msg'=>'用户密码错误，请检查！');
                      return $this->renderText(json_encode($msg));
                  }
                  
              }else{
                  $msg = array('error'=>1,'msg'=>'用户不存在，请检查！');
                  return $this->renderText(json_encode($msg));
              }
          }
      }
  }
  
  public function executeReg(sfWebRequest $request)
  {
      sfConfig::set('sf_web_debug',false);
        if($request->isMethod('POST')){
                  $phone = floatval($request->getParameter('phone',0));
                  $code = (int)$request->getParameter('phone_code',0);
                  $password = trim($request->getParameter('password',0));
                  $msg = array('error'=>0,'msg'=>'');

                  if(strlen($phone) != 11){
                      $msg = array('error'=>1,'msg'=>'手机号码填写错误，请检查！');
                      return $this->renderText(json_encode($msg));
                  }elseif(strlen($code) != 6){
                      $msg = array('error'=>1,'msg'=>'验证码填写错误，请检查！');
                      return $this->renderText(json_encode($msg));
                  }elseif(strlen($password) < 32 ){
                      $msg = array('error'=>1,'msg'=>'密码长度错误，请检查！');
                      return $this->renderText(json_encode($msg));
                  }else{

                    $has_user = Doctrine::getTable('User')->findOneByPhone($phone);  

                    if($has_user){
                        $msg = array('error'=>1,'msg'=>'手机号已经注册！');
                        return $this->renderText(json_encode($msg));
                    }else{
                        $sms = Doctrine::getTable('SmsMessage')->createQuery()->where('phone = ?',$phone)->andWhere("code = ?",$code)->andWhere('is_use = 0')->orderBy('created_at desc')->execute();
                        if(count($sms) == 1 ){
                            $sms = $sms->getFirst();
                            $sms->setIsUse(1)->save();
                            $user = new User();
                            $user->setPhone($phone)->setPassword($password)->setCover('')->save();
                            $msg = array('error'=>0,'msg'=>'注册成功！','id'=>$user->getId());
                            return $this->renderText(json_encode($msg));
                        }else{
                            $msg = array('error'=>1,'msg'=>'验证码不存在！');
                            return $this->renderText(json_encode($msg));
                        }
                      }
                  }
        }
  }
}
